package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 预约设置
 */
@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @Reference
    private OrderSettingService orderSettingService;

    /**
     *  Excel文件上传，并解析内容保存到数据库
     * @param excelFile
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile")MultipartFile excelFile){
        try {
            // 读取Excel文件数据
            List<String[]> list = POIUtils.readExcel(excelFile);
            if (list != null && list.size()>0){
                List<OrderSetting> orderSettingList = new ArrayList<>();
                for (String[] strings : list) {
                    OrderSetting orderSetting = new OrderSetting(new Date(strings[0]),Integer.parseInt(strings[1]));
                    orderSettingList.add(orderSetting);
                }
                orderSettingService.add(orderSettingList);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
        return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }

    // 根据月份查询预约设置信息，用于数据回显
    @RequestMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String date){  // 参考格式：yyyy-MM
        try {
            List<Map> list = orderSettingService.getOrderSettingByMonth(date);
            // 获取预约设置成功
            return new Result(true,MessageConstant.GET_ORDERSETTING_SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            // 获取预约设置失败
            return new Result(false,MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    // 根据指定日期修改可预约人数
    @RequestMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        try{
            orderSettingService.editNumberByDate(orderSetting);
            // 预约设置成功
            return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.ORDERSETTING_FAIL);
        }
    }

    // controller添加导出方法

    /**
     * 使用response返回excel文件
     * @param date
     */
    @RequestMapping("/downloadOrderSetting")
    public void downloadOrderSetting(String date, HttpServletResponse response){
        List<Map> orderSettingByMonth = orderSettingService.getOrderSettingByMonth(date);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            // 在内存中创建工作一个工作簿对象，用于生成excel文件
            XSSFWorkbook excel = new XSSFWorkbook();
            // 创建工作表，指定工作名称
            XSSFSheet sheet = excel.createSheet("预约信息");
            // 创建标题行，第一行
            XSSFRow headRow = sheet.createRow(0);
            // 创建单元格，0表示第一个单元格
            headRow.createCell(0).setCellValue("日期");
            headRow.createCell(1).setCellValue("可预约数");
            headRow.createCell(2).setCellValue("已预约数");
            // 遍历行数据
            for (int i = 0; i < orderSettingByMonth.size(); i++) {
                XSSFRow row = sheet.createRow(i+1);
                row.createCell(0).setCellValue(orderSettingByMonth.get(i).get("date")+"");
                row.createCell(1).setCellValue(orderSettingByMonth.get(i).get("number")+"");
                row.createCell(2).setCellValue(orderSettingByMonth.get(i).get("reservations")+"");
            }
            // 导出设置
            // 导出文件名及编码格式
            String fileNameURL = URLEncoder.encode(date+"预约信息.xlsx","UTF-8");
            // 响应字符集编码
            response.setCharacterEncoding("UTF-8");
            // 响应头
            response.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);
            // 响应文件类型
            response.setContentType("application/octet-stream");
            // 刷新缓冲
            response.flushBuffer();;
            // 通过输出流将workbook工作簿对象下载到磁盘
            excel.write(outputStream);
            outputStream.flush();//刷新
            // 关闭资源
            outputStream.close();//关闭
            excel.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
